from flask import Blueprint, session, render_template, flash, send_from_directory, url_for, request
from core.personal.form import PersonalForm, ProveForm, is_personal, submit_personal, is_prove, submit_prove
from models import User, to_img, Prove

personal_blueprint = Blueprint('personal', __name__)

@personal_blueprint.route('/personal', methods=['GET', 'POST'])
def personal():
    uid = session.get('uid')
    form1 = PersonalForm()
    form2 = ProveForm()

    if request.method == 'POST':
        if is_personal(form1):
            if submit_personal(form1, uid):
                flash('更新个人信息成功')
            else:
                flash('更新个人信息失败')

        if is_prove(form2):
            if submit_prove(form2, uid):
                flash('上传身份证明成功')
            else:
                flash('上传身份证明失败')

    user = User.get_by_uid(uid)
    prove = Prove.get_by_uid(uid)

    return render_template('page/personal/index.html', form1=form1, form2=form2, username=user.username, role=user.role,
                           text=user.text, img_url=url_for('personal.personal_user_img',username=user.username),status=prove.status,unpass=prove.unpass)

@personal_blueprint.route('/personal/user/<string:username>')
def personal_username(username):
    user = User.get_by_username(username)
    return render_template('page/shared/personal.html',username=user.username, role=user.role,
                           text=user.text, img_url=url_for('personal.personal_user_img',username=user.username))

@personal_blueprint.route('/personal/user/<string:username>/img')
def personal_user_img(username):
    user = User.get_by_username(username)
    if user.img:
        return to_img(user.img)
    return send_from_directory('static', 'default.jpg', mimetype='image/jpeg')


@personal_blueprint.route('/personal/user/<string:username>/prove/img')
def personal_prove_img(username):
    uid = User.get_by_uid(username)
    prove = Prove.get_by_uid(uid)
    if prove.img:
        return to_img(prove.img)
    return send_from_directory('static', 'default.jpg', mimetype='image/jpeg')